package com.csii.adhoc.info.role.serviceImpl;

import com.csii.adhoc.exception.ParamValidityException;
import com.csii.adhoc.id.UidGenerator;
import com.csii.adhoc.info.role.RolePo;
import com.csii.adhoc.info.role.mapper.RoleMapper;
import com.csii.adhoc.info.role.service.RoleService;
import com.csii.adhoc.info.user.service.UserService;
import com.csii.common.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description: 角色实现类
 * @author: panChuanJiang
 * @create: 2021-01-27 16:40
 */
@Service("roleService")
@Slf4j
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleMapper roleMapper;
    @Autowired
    private UidGenerator uidGenerator;
    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public void roleMaintain(RolePo rolePo, String optMode) {
        switch (optMode) {
            case CommonConstant.OPT_MODE_ADD:
                rolePo.setCreatedBy(rolePo.getUpdatedBy())
                        .setCreatedDt(rolePo.getUpdatedDt());
                insertOneRole(rolePo);
                break;
            case CommonConstant.OPT_MODE_DELETE:
                deleteRoleByPrimaryKey(rolePo.getRoleId());
                break;
            case CommonConstant.OPT_MODE_UPDATE:
                updateRoleByPrimaryKey(rolePo);
                break;
            default:
                log.error("optMode值不合法:" + optMode);
                throw new ParamValidityException("optMode值不合法:" + optMode);
        }
    }

    @Transactional
    public void updateRoleByPrimaryKey(RolePo rolePo) {
        if (StringUtils.isEmpty(rolePo.getRoleId())) {
            throw new ParamValidityException("roleId值为空:" + rolePo.getRoleId());
        }
        roleMapper.updateRoleByKey(rolePo);
    }

    @Transactional
    public void deleteRoleByPrimaryKey(String roleId) {
        if (StringUtils.isEmpty(roleId)) {
            throw new ParamValidityException("roleId值为空:" + roleId);
        }
        roleMapper.deleteRoleByPrimaryKey(roleId);
        userService.updateUserClearRoleId(roleId);
    }

    @Transactional
    public void insertOneRole(RolePo rolePo) {
        rolePo.setRoleId(uidGenerator.getUID() + "");
        roleMapper.insertOneRole(rolePo);
    }

    @Override
    public List<RolePo> selectListRole(RolePo rolePo) {
        return roleMapper.selectListRole(rolePo);
    }
}
